package com.ruoyi.parent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SendCodeUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.parent.domain.ParentLoginVo;
import com.ruoyi.parent.domain.ParentVo;
import com.ruoyi.parent.mapper.ParentMapper;
import com.ruoyi.parent.service.IParentService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 家长管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-17
 */
@Service
public class ParentServiceImpl implements IParentService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    protected Validator validator;
    @Autowired
    private ParentMapper parentMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询家长管理
     *
     * @param id 家长管理主键
     * @return 家长管理
     */
    @Override
    public ParentVo selectParentById(Long id) {
        return parentMapper.selectParentById(id);
    }

    /**
     * 查询家长管理列表
     *
     * @param parentVo 家长管理
     * @return 家长管理
     */
    @Override
    public List<ParentVo> selectParentList(ParentVo parentVo) {
        return parentMapper.selectParentList(parentVo);
    }

    /**
     * 新增家长管理
     *
     * @param parentVo 家长管理
     * @return 结果
     */
    @Override
    public int insertParent(ParentVo parentVo) {
//        设置创建时间
        parentVo.setCreateTime(DateUtils.getNowDate());
//        格式转换成sysUser类型再插入
        SysUser convert = ParentVo.Convert(parentVo);
//        加密
        convert.setPassword(SecurityUtils.encryptPassword(convert.getPassword()));
//        绑定角色
        convert.setRoleIds(new Long[]{2L});
        return sysUserService.insertUser(convert);
    }

    /**
     * 修改家长管理
     *
     * @param parentVo 家长管理
     * @return 结果
     */
    @Override
    public int updateParent(ParentVo parentVo) {
        parentVo.setUpdateTime(DateUtils.getNowDate());
        return sysUserMapper.updateUser(ParentVo.Convert(parentVo));
    }

    /**
     * 导入家长数据
     *
     * @param parentList      家长列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importParent(List<ParentVo> parentList, Boolean isUpdateSupport, String operName) {

        if (StringUtils.isNull(parentList) || parentList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ParentVo parent : parentList) {
            try {
                // 验证是否存在这个用户
                ParentVo c = parentMapper.selectParentById(parent.getId());
                if (StringUtils.isNull(c)) {
                    BeanValidators.validateWithException(validator, parent);
                    parent.setPassword(SecurityUtils.encryptPassword(parent.getPassword()));
                    parent.setCreateBy(operName);
                    insertParent(parent);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、家长 " + parent.getPatriarchName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, parent);
                    parent.setId(c.getId());
                    parent.setUpdateBy(operName);
                    updateParent(parent);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、家长 " + parent.getPatriarchName() + " 更新成功");
                } else {
                    System.out.println(3);
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、家长 " + parent.getPatriarchName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、家长 " + parent.getPatriarchName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public AjaxResult sendPhoneCode(ParentLoginVo parentLoginVo) {
        List<ParentVo> parentVos = parentMapper.selectParentByUserName(parentLoginVo.getUsername());
        if (parentVos != null) {
            String code = SendCodeUtils.message(parentLoginVo.getUsername());
            String redisKey = parentLoginVo.getUsername() + parentLoginVo.getType();
            redisCache.setCacheObject(redisKey, code, 5, TimeUnit.MINUTES);
            return AjaxResult.success("发送成功");
        } else {
            return AjaxResult.error("用户不存在");
        }
    }

    @Override
    public AjaxResult getUserInfo(String username) {
        QueryWrapper<ParentLoginVo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username);
        wrapper.select("user_id", "user_name", "nick_name", "avatar", "real_name", "phonenumber", "email", "create_time");
        return AjaxResult.success(parentMapper.selectOne(wrapper));
    }

    @Override
    public AjaxResult rePassword(ParentLoginVo parentLoginVo) {
        UpdateWrapper<ParentLoginVo> wrapper = new UpdateWrapper<>();
        //判断验证码是否正确
        String redisKey = parentLoginVo.getUsername() + parentLoginVo.getType();
        Object cachedObject = redisCache.getCacheObject(redisKey);
        //验证码存在且正确
        if (parentLoginVo.getCode().equals(cachedObject)) {
            wrapper.eq("user_name", parentLoginVo.getUsername()).set("password", SecurityUtils.encryptPassword(parentLoginVo.getPassword()));
            parentMapper.update(wrapper);
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.error("验证码过期/验证码不正确");
        }
    }

    @Override
    public AjaxResult changeInfo(ParentLoginVo parentLoginVo) {
        UpdateWrapper<ParentLoginVo> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_name", parentLoginVo.getUsername()).set("avatar", parentLoginVo.getAvatar()).set("nick_name", parentLoginVo.getNickName());
        parentMapper.update(wrapper);
        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult changePass(ParentLoginVo parentLoginVo) {
        //判断原密码是否正确
        QueryWrapper<ParentLoginVo> wrapper = new QueryWrapper<>();
        UpdateWrapper<ParentLoginVo> wrapper1 = new UpdateWrapper<>();
        wrapper.eq("user_name", parentLoginVo.getUsername());
        wrapper.select("password");
        wrapper1.eq("user_name", parentLoginVo.getUsername());
        ParentLoginVo parentLoginVo1 = parentMapper.selectOne(wrapper);
        //判断旧密码输入是否正确
        if (!SecurityUtils.matchesPassword(parentLoginVo.getPassword(), parentLoginVo1.getPassword())) {
            return AjaxResult.error("旧密码输入错误");
        } else {
            //更新密码
            wrapper1.set("password", SecurityUtils.encryptPassword(parentLoginVo.getNewPassword()));
            parentMapper.update(wrapper1);
            return AjaxResult.success("修改成功");
        }
    }
}


